package com.cipta.lomob.fragments;

import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONObject;

import tv.lomob.api.Lomob;
import tv.lomob.api.LomobResponseHandler;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.cipta.lomob.LomobManager;
import com.cipta.lomob.R;
import com.cipta.lomob.base.BaseFragment;

public class UploadFragment extends BaseFragment {
	private Button chooseButton;
	private Button uploadButton;
	private EditText editTextTitle;
	private Spinner spinnerCategories;
	private Spinner spinnerRestriction;
	private String[] categories;
	private String[] restricted;
	String title;
	String category;
	String restrict;
	private long fileSize = 0;
	private long totalSizeTransfer = 0;
	public static final int READ_REQUEST_CODE = 10101;
	private ProgressDialog progressDialog = null;
	private FTPClient clientFTP;
	private Context context;
	String FTPHost = "";
	String FTPUser = "";
	String FTPPass = "";
	int FTPPort = 21;
	boolean isReady = false;
	File uploadFile = null;
	private UploadProgressHandler handler;
	public static final int CLOSE_PROGRESS = 1;
	public static final int UPDATE_PROGRESS = 2;
	public static final int SHOW_PROGRESS = 3;
	private boolean transferComplete = false;

	public UploadFragment(Context iCcontext) {
		this.context = iCcontext;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initializeProcess();
		initializeActions();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_upload, container,
				false);
		initializeViews(rootView);
		return rootView;
	}

	@Override
	public void initializeViews(View view) {
		super.initializeViews(view);
		chooseButton = (Button) view.findViewById(R.id.buttonChooseFile);
		uploadButton = (Button) view.findViewById(R.id.buttonUploadFile);
		editTextTitle = (EditText) view.findViewById(R.id.editTxtTitle);
		spinnerCategories = (Spinner) view.findViewById(R.id.spinnerCategories);
		spinnerRestriction = (Spinner) view
				.findViewById(R.id.spinnerRestriction);
	}

	@Override
	public void initializeProcess() {
		// //add listener
		chooseButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				openFileBrowser();
			}
		});

		uploadButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				uploadFile(uploadFile);
			}
		});

		String token = LomobManager.getInstance().getUser().optString("token");
		// get categories
		Lomob.getCategories(new LomobResponseHandler() {

			@Override
			public void onSuccess(JSONObject result) {
				try {
					JSONArray categoriesObject = result
							.optJSONArray("categories");
					int total = categoriesObject.length();
					categories = new String[total];

					for (int i = 0; i < total; i++) {
						categories[i] = categoriesObject.optString(i);
					}
					ArrayAdapter<String> spinnerCategoriesAdapter = new ArrayAdapter<String>(
							getActivity(),
							android.R.layout.simple_spinner_item, categories);
					spinnerCategories.setAdapter(spinnerCategoriesAdapter);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

			@Override
			public void onError(String message) {
				categories = new String[1];
				categories[0] = "-";
			}
		});

		// get categories
		Lomob.getRestricted(new LomobResponseHandler() {

			@Override
			public void onSuccess(JSONObject result) {
				try {
					JSONArray restrictedObject = result
							.optJSONArray("restricted");
					int total = restrictedObject.length();
					restricted = new String[total];

					for (int i = 0; i < total; i++) {
						restricted[i] = restrictedObject.optString(i);
					}

					ArrayAdapter<String> spinnerRestrictionAdapter = new ArrayAdapter<String>(
							getActivity(),
							android.R.layout.simple_spinner_item, restricted);
					spinnerRestriction.setAdapter(spinnerRestrictionAdapter);

				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

			@Override
			public void onError(String message) {
				restricted = new String[1];
				restricted[0] = "-";
			}
		});

		Lomob.getFTPAccount(token, new LomobResponseHandler() {

			@Override
			public void onSuccess(JSONObject result) {
				Log.i("FTP", result.toString());
				FTPHost = result.optString("host");
				FTPPort = result.optInt("port");
				FTPUser = result.optString("username");
				FTPPass = result.optString("password");
				isReady = true;
				clientFTP = new FTPClient();
				try {
					if (android.os.Build.VERSION.SDK_INT > 9) {
						StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
								.permitAll().build();
						StrictMode.setThreadPolicy(policy);
					}

					clientFTP.connect(FTPHost, FTPPort);
					clientFTP.login(FTPUser, FTPPass);
					clientFTP.setType(FTPClient.TYPE_BINARY);
				} catch (Exception ex) {
					ex.printStackTrace();
					try {
						Log.e("API", ex.getMessage());
					} catch (Exception ftpException) {
						ftpException.printStackTrace();
					}
				}
			}

			@Override
			public void onError(String message) {
				isReady = false;
				Log.e("FTP", message);
			}
		});
	}

	private void uploadFile(final File file) {
		if (!isReady) {
			Toast.makeText(getActivity(), "Upload failed...",
					Toast.LENGTH_SHORT).show();
			return;
		}
		// get parameter
		title = editTextTitle.getText().toString();
		category = (String) spinnerCategories.getSelectedItem();
		restrict = (String) spinnerRestriction.getSelectedItem();

		fileSize = file.length();
		totalSizeTransfer = 0;
		try {
			handler = new UploadProgressHandler();
			progressDialog = new ProgressDialog(context);
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.setMessage("Uploading...0%");
			progressDialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface arg0) {
					try {
						clientFTP.abortCurrentDataTransfer(true);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (FTPIllegalReplyException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});

			AsyncTask<Void, Void, Void> uploadTask = new AsyncTask<Void, Void, Void>() {

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					progressDialog.show();
				}

				@Override
				protected void onPostExecute(Void result) {
					super.onPostExecute(result);
					if (transferComplete) {
						Lomob.setVideoProfile(LomobManager.getInstance()
								.getUser().optString("token"), title, category,
								restrict, uploadFile.getName(),
								new LomobResponseHandler() {
									@Override
									public void onSuccess(JSONObject result) {
										Toast.makeText(getActivity(), "Video Uploaded", Toast.LENGTH_SHORT).show();
										if (progressDialog != null) {
											if (progressDialog.isShowing()) {
												progressDialog.dismiss();
											}
										}
									}

									@Override
									public void onError(String message) {
										Log.e("API", "set video profile error");
										Toast.makeText(getActivity(), "Upload failed: " + message, Toast.LENGTH_SHORT).show();
										if (progressDialog != null) {
											if (progressDialog.isShowing()) {
												progressDialog.dismiss();
											}
										}
									}
								});
					}else{
						Toast.makeText(getActivity(), "Upload failed" , Toast.LENGTH_SHORT).show();
						if (progressDialog != null) {
							if (progressDialog.isShowing()) {
								progressDialog.dismiss();
							}
						}
					}

				}

				@Override
				protected Void doInBackground(Void... params) {
					try {
						clientFTP.upload(file, new TransferFileListener());
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (FTPIllegalReplyException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (FTPException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (FTPDataTransferException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (FTPAbortedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return null;
				}

			};

			uploadTask.execute();

			// start upload to server

		} catch (Exception ex) {
			ex.printStackTrace();
			try {
				Log.e("API", ex.getMessage());
			} catch (Exception ftpException) {
				ftpException.printStackTrace();
			}
		}
	}

	// listner for transfer file
	public class TransferFileListener implements FTPDataTransferListener {
		@Override
		public void aborted() {
			handler.sendEmptyMessage(CLOSE_PROGRESS);
		}

		@Override
		public void completed() {
			transferComplete = true;
		}

		@Override
		public void failed() {
			handler.sendEmptyMessage(CLOSE_PROGRESS);
		}

		@Override
		public void started() {

		}

		@Override
		public void transferred(int length) {
			totalSizeTransfer += length;
			int progress = (int) ((totalSizeTransfer * 100) / ((int) fileSize));
			Bundle bundle = new Bundle();
			bundle.putInt("complete", progress);
			Message message = new Message();
			message.what = UPDATE_PROGRESS;
			message.setData(bundle);
			handler.sendMessage(message);
		}

	}

	public void openFileBrowser() {
		// Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
		Intent intent = new Intent(Intent.ACTION_PICK,
				MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
		// intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("video/*");
		// intent.setType("*/*");
		startActivityForResult(intent, READ_REQUEST_CODE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode,
			Intent resultData) {
		super.onActivityResult(requestCode, resultCode, resultData);
		if (requestCode == READ_REQUEST_CODE
				&& resultCode == Activity.RESULT_OK) {
			Uri uri = null;
			if (resultData != null) {
				uri = resultData.getData();
				String path = getRealPathFromURI(uri);
				uploadFile = new File(path);
			}
		}
	}

	private String getRealPathFromURI(Uri contentURI) {
		// // Will return "image:x*"
		// String wholeID = DocumentsContract.getDocumentId(contentURI);
		//
		// // Split at colon, use second item in the array
		// String id = wholeID.split(":")[1];
		//
		// String[] column = { MediaStore.Video.Media.DATA };
		//
		// // where id is equal to
		// String sel = MediaStore.Video.Media._ID + "=?";
		//
		// Cursor cursor = getActivity().getContentResolver().query(
		// MediaStore.Video.Media.EXTERNAL_CONTENT_URI, column, sel,
		// new String[] { id }, null);
		//
		// String filePath = "";
		//
		// int columnIndex = cursor.getColumnIndex(column[0]);
		//
		// if (cursor.moveToFirst()) {
		// filePath = cursor.getString(columnIndex);
		// }
		// cursor.close();
		// return filePath;
		String[] proj = { MediaStore.Audio.Media.DATA };
		CursorLoader loader = new CursorLoader(getActivity(), contentURI, proj,
				null, null, null);
		Cursor cursor = loader.loadInBackground();
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	private class UploadProgressHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_PROGRESS:

				break;
			case CLOSE_PROGRESS:
				progressDialog.dismiss();
				break;
			case UPDATE_PROGRESS:
				Bundle bundle = msg.getData();
				int progress = bundle.getInt("complete");
				progressDialog.setMessage("Uploading..." + progress + "%");
				break;
			default:
				break;
			}
		}

	}

}
